import Vue from 'vue'
// 1. 路由引入相关的库文件
import VueRouter from 'vue-router'
// 4.导入 登录 的单文件组件(也是路由组件)
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/welcome.vue'
import Users from '../components/user/users.vue'
import Rights from '../components/power/rights.vue'
import Roles from '../components/power/roles.vue'
import Cate from '../components/goods/cate.vue'
import Params from '../components/goods/params.vue'
import GoodsList from '../components/goods/list.vue'
import Add from '../components/goods/add.vue'
import Order from '../components/order/order.vue'
import Report from '../components/report/report.vue'


Vue.use(VueRouter)

// 5.配置路由规则
const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/login'
  },
  // login 登录的路由规则
  {
    path: '/login',
    component: Login
  },
  // home 后台主页的路由规则
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [{
        path: '/welcome',
        component: Welcome,
      },
      // 用户列表的路由规则
      {
        path: '/users',
        component: Users
      },
      // 权限列表的路由规则
      {
        path: '/rights',
        component: Rights
      },
      // 角色列表的路由规则
      {
        path: '/roles',
        component: Roles
      },
      // 商品分类的路由规则
      {
        path: '/categories',
        component: Cate
      },
      // 分类参数的路由规则
      {
        path: '/params',
        component: Params
      },
      // 商品列表的路由规则
      {
        path: '/goods',
        component: GoodsList
      },
      // 添加商品的路由规则
      {
        path: '/goods/add',
        component: Add
      },
      // 订单管理的路由规则
      {
        path: '/orders',
        component: Order
      },
      // 数据统计的路由规则
      {
        path: '/reports',
        component: Report
      }
    ]
  },
]

// 创建路由实例
const router = new VueRouter({
  routes
})


// 挂载路由导航守卫控制访问权限
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数表示放行
  // next() 放行 next('/login') 强制跳转到/login
  if (to.path === '/login') return next() //登陆页面直接放行
  // 获取 token
  const tokenStr = sessionStorage.getItem('token')
  // 疑惑：这样假token也能登录！！！！
  if (!tokenStr) return next('/login')
  next()
})

export default router